Uec3.AddSaleReturnItemWindow = Ext.extend(Ext.UecWindow,{

	editCount : 0,
	
	constructor : function(config){
		
		this.partSourceCombo = Uec3.App.dictionary.getCombo("part_source",{hiddenName:'source',fieldLabel:'来源',allowBlank : true,width:90});
		
		this.northPanel = new Ext.FormPanel({
			frame :true,
			border:false,
			region : 'north',
			height:50,
			items:[
				{ 
					layout:'hbox',
					layoutConfig:
					{      
						align:'middle' 
					},
					style:'padding:0px;fontSize:13px;',													
					items:[
						{xtype:'label',text:'单据号:',style:{width:'50px'}},
						{xtype:'textfield',name:'codeOfSeller',style:{width:'100px'}},
						{xtype:'label',text:'零件编码:',style:{marginLeft:'0px',width:'67px'}},
						{xtype:'textfield',name:'code',style:{width:'100px'}},
						{xtype:'label',text:'零件名称:',style:{marginLeft:'0px',width:'67px'}},
						{xtype:'textfield',name:'name',style:{width:'100px'}},
						{xtype:'label',text:'来源:',style:{marginLeft:'0px',width:'38px'}},
						this.partSourceCombo,
						{xtype:'label',text:'品牌:',style:{marginLeft:'0px',width:'38px'}},
						{xtype:'textfield',name:'brand',style:{width:'90px'}},
						{xtype:'label',text:'产地:',style:{marginLeft:'0px',width:'38px'}},
						{xtype:'textfield',name:'origin',style:{width:'90px'}},
						{xtype:'button',text:'查找',style:{marginLeft:'15px',width:'75px'},scope:this,handler:this.searchSaleItemsByCondition}
				]
			}]			 
		});
		
		this.centerPanel = new Ext.TabPanel({
			resizeTabs:true,
			minTabWidth: 115,
			title:'销售明细',
			region:'center',
			forceLayout:true,
			enableTabScroll:true,
			layoutOnTabChange:true,
			deferredRender :true,
			defaults: {autoScroll:true}
		});
		
		this.saleItemStore = new Ext.data.JsonStore({
			root:'saleItem',
			pruneModifiedRecords:true,
			fields:[
				{name: 'partId'},
				{name: 'sourceInventoryId',mapping:'inventoryIdBySeller'},//-- 卖方的零件库存ID
				{name: 'code'},          				
				{name: 'source'},
				{name: 'name'},
				{name: 'carModel'},
				{name: 'nameEn'},
				{name: 'pyCode'},
				{name: 'measurementUnit'},
				{name: 'partCategoryId'},
				{name: 'level1Name'},
				{name: 'level2Name'},
				{name: 'level1Id'},
				{name: 'brand'},
				{name: 'origin'},
				{name: 'retailPrice',mapping:'price'},           //-- 售价
				{name: 'saleQuantity',mapping:'quantity'},      //-- 销售数量
				{name: 'quantity',mapping:''},	 	   			 //-- 退货数量	
				{name: 'retailAmount',mapping:''},                //--退货金额
				{name: 'storeId'},
				{name: 'storePyCode'},
				{name: 'storeName'},
				{name: 'shelf'},
				{name: 'isSelected'}
			]                  
		});
		
		this.expressItemStore = new Ext.data.JsonStore({
			root:'expressItem',
			fields: [
				{name: 'partId'},
				{name: 'sourceInventoryId',mapping:'inventoryIdBySeller'}, 
				{name: 'code'},          				
				{name: 'source'},
				{name: 'name'},
				{name: 'carModel'},
				{name: 'nameEn'},
				{name: 'pyCode'},
				{name: 'measurementUnit'},
				{name: 'partCategoryId'},
				{name: 'level1Name'},
				{name: 'level2Name'},
				{name: 'level1Id'},
				{name: 'brand'},
				{name: 'origin'},                                    
				{name: 'retailPrice'},								 //-- 售价
				{name: 'saleQuantity',mapping:'saleQuantity'},      //-- 销售数量
				{name: 'quantity',mapping:''},                       //-- 退货数量
				{name: 'retailAmount',mapping:''},                //--退货金额
				{name: 'storeId'},
				{name: 'storeName'},
				{name: 'shelf'},
				{name: 'isSelected'}
			]
		});		
		
		config = Ext.apply(config||{},{items:[this.northPanel,this.centerPanel]});
		
		Uec3.AddSaleReturnItemWindow.superclass.constructor.call(this,config);
	},
	
	 //private
	initComponent:function(){
		Uec3.AddSaleReturnItemWindow.superclass.initComponent.call(this);
	},
	
	//private 
	initEvents : function(){
		Uec3.AddSaleReturnItemWindow.superclass.initEvents.call(this);
		this.partSourceCombo.getStore().load();
		this.saleItemStore.on('load',this.renderSaleItemRecord,this);
		this.expressItemStore.on('load',this.renderExpressItemRecord,this);
	},
	
	getGrid4Tab : function(store){
		
		var grid4Tab = new Ext.grid.EditorGridPanel({
			frame : false,
			columnLines :true,
			stripeRows: true,
			height:126,                   
			enableHdMenu : false,
			stripeRows: true,
			store:store,
			viewConfig:{scrollOffset:20},
			autoScroll : true,  	            
			clicksToEdit:1,
			scope:this,
			columns:[ 
				new Ext.grid.RowNumberer(),
			    {
				 header:'操作',
				 xtype:'anchorcolumn',
				 width : 100,
				 dataIndex : 'act',
				 items:[
				   {
					text:"退货",
					scope:this,
					//permissionId:25,
					handler:this.addToSaleReturn,
					getVisiblity : this.showAddLink
				   },{
					text:"取消",
					scope:this,
					//permissionId:25,
					handler:this.deleteSaleReturnItem,
					getVisiblity : this.showCancelLink
				   }
				 ]
				},
				{header:'是否已选',dataIndex : 'isSelected'},
				{header:'退货数量',dataIndex:'quantity',
				  	editor:new Ext.form.NumberField({
						 allowBlank: false,
						 allowNegative: false
					})	             			 
				},
				{header:'零件编码',dataIndex:'code'},
				{header:'零件名称',dataIndex:'name'},
				{header:'车型',dataIndex:'carModel'},
				{header:'来源',dataIndex:'source',renderer:Ext.util.Format.comboRenderer(this.partSourceCombo)},
				{header:'单位',dataIndex:'measurementUnit'},
				{header:'销售数量',dataIndex:'saleQuantity'},
				{header:'销售价',dataIndex:'retailPrice'},                   	
				{header:'品牌',dataIndex:'brand'},
				{header:'产地',dataIndex:'origin'},
				{header:'仓库',dataIndex:'storeName'},
				{header:'仓位',dataIndex:'shelf'}				
			],
			listeners : {
				'validateedit':function(e){
					if(e.field == 'quantity'){
						if(e.record.data.saleQuantity < e.value){
							Ext.MessageBox.alert("提示","退货数量不能大于销售数量!");
			   				return false;
						}
						if(e.value == 0){
							Ext.MessageBox.alert("提示","请正确选择退货数量!");
			   				return false;
						}
					}
				},
				'mouseout':function(e){
					if(grid4Tab.activeEditor){
						this.editCount++;
						if(this.editCount == 2){
							this.editCount = 0;
							grid4Tab.stopEditing();
						}
					}
				}
			}
		}); 
		return grid4Tab;
	},
	
	renderSaleItemRecord : function(store,records,options){
		this.renderIsSelected(store);
	},
	
	renderExpressItemRecord : function(store,records,options){
		this.renderIsSelected(store);
	},
	
	renderIsSelected : function(store){
		var saleReturnItemRecords = this.params.saleReturnItemRecords;
		if(saleReturnItemRecords){			
			Ext.each(saleReturnItemRecords,function(record,index){
				var index = store.findExact('sourceInventoryId',record.get('sourceInventoryId'));
				if(index != -1){
					var loadedRecord = store.getAt(index);
					loadedRecord.set('quantity',record.get('quantity'));
					loadedRecord.set('isSelected','是');
				}
			});
		}
	},
	
	addToSaleReturn : function(grid, rowIndex, colIndex, item, e){
		var fn = this.params.fn;
		if(fn && Ext.isFunction(fn)){
			var record = grid.getStore().getAt(rowIndex);
			if(!record.get('quantity') || record.get('quantity') == 0){
				Ext.MessageBox.alert("提示",'请选择正确的退货数量!');
				return false;
			}else{
				record.set('isSelected','是');
				record.set('isAdd',true);
				fn(record);
			}
		}		
		grid.getView().refresh();
	},
	
	deleteSaleReturnItem : function(grid, rowIndex, colIndex, item, e){
		var fn = this.params.fn;
		if(fn && Ext.isFunction(fn))
		var record = grid.getStore().getAt(rowIndex);
		record.set('quantity','');
		record.set('isSelected','否');
		record.set('isAdd',false);
		fn(record);		
		grid.getView().refresh();
	},
	
	showAddLink : function(value,meta,record,rowIndex,colIndex,store){
		return true;
	},
	
	showCancelLink : function(value,meta,record,rowIndex,colIndex,store){
		if(record.get('isSelected') == '是'){
			return true;
		}
		return false;
	},
	
	addTab : function(title,store){
		var grid = this.getGrid4Tab(store);
		grid.setHeight(this);
		this.centerPanel.add({
			title: title,
			iconCls: 'tabs',
			layout:'fit',
			items:[grid],
			closable:false
		}).show();
		this.centerPanel.setActiveTab(0);
	},
	
	searchSaleItemsByCondition : function(){
		if(!this.northPanel.getForm().isValid()){
			return;
		}else{
			var partnerIdBySeller = this.params.partnerComb.getValue();
			var queryParam = this.northPanel.getForm().getValues();
			if(Ext.isEmpty(partnerIdBySeller)){
				Ext.MessageBox.alert("提示","请选择客户");
			}else{		       	   	      
				queryParam.partnerIdBySeller = partnerIdBySeller;
				var myMask = new Ext.LoadMask(this.el,{msg :"正在查询相关销售信息,请稍后..."});
				myMask.show();
				Ext.Ajax.request({
					url : Uec3.App.Constants.homeUrl+"/saleReturn/queryAllItems.do",
					method:'POST', 
					params :{queryParam:Ext.encode(queryParam)},                   
					callback :function(options,success,response){
						myMask.hide();
					},
					success : function(response,options) {
						var resp = Ext.decode(response.responseText);
						if(resp.success){
							if(resp.length == 0){
								Ext.MessageBox.alert("提示",'未查询到来自该客户的销售信息...');
							}else{
								this.centerPanel.removeAll();
								if(resp.saleItem){
									this.saleItemStore.loadData(resp);
									this.addTab('库存件',this.saleItemStore);
								}
								if(resp.expressItem){
									this.expressItemStore.loadData(resp);
									this.addTab('急件',this.expressItemStore);
								}  
							}							                              	 	                                 	 	 
						}else{
							Ext.MessageBox.alert("提示",resp.msg);
						} 
					},
					failure : function(response,options) {
						Ext.MessageBox.alert("提示","数据加载异常");
					},
					scope:this
				});
			} 
   		}	
	}	
});

Uec3.AddSaleReturnItemModule = Ext.extend(Ext.app.Module,{
	id: 'saleReturnItemAdd',	
	
	createWindow : function(params){			
		var desktop = this.app.getDesktop();
        var win = desktop.getWindow('addSaleReturnItemWindow');
		if(!win){
			win = desktop.createWindowNoTask({
				id: "addSaleReturnItemWindow",
				title: '销售退货明细增加',
				params : params,
				width: 1000,
				height: 500,
				minWidth:1000,
				minHeight:500,
				iconCls: 'acc-icon',
				shim: false,
				modal :true,
				animCollapse: false,
				constrainHeader: true,
				maximizable: true,
				minimizable : false,
				taskbuttonTooltip: "销售退货明细增加",
				layout: "border"         
			},Uec3.AddSaleReturnItemWindow);
		}else{
			win.params = params;
		}	
		win.show();
	} 
});